import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { GqlArgumentsHost } from '@nestjs/graphql';
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    if (host.getType() + '' === 'graphql') {
      this.handleGqlException(host, exception);
    } else {
      this.handleRestfulException(host, exception);
    }
  }

  private handleGqlException(host: ArgumentsHost, exception: HttpException) {
    const context = GqlArgumentsHost.create(host).getContext();
    console.log(exception.getResponse(), context.res);
  }
  private handleRestfulException(
    host: ArgumentsHost,
    exception: HttpException,
  ) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR; // 获取异常状态码
    // 设置错误信息
    const message = exception.message;
    const errorMessage = {
      code: status,
      message,
    };
    response.status(status);
    response.send(errorMessage);
  }
}
